package network.tcp;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class TcpFileServer {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream stream = null;
        OutputStream out = null;
        FileOutputStream fileOS = null;

        try {
            //1.服务端提供地址
            serverSocket = new ServerSocket(10001);

            //2.等待客户端连接
            socket = serverSocket.accept();//阻塞式监听，一直等待客户端连接

            //3.接受客户端消息 IO流 文件流
            stream = socket.getInputStream();
            out = socket.getOutputStream();
            //使用管道流，文件流，修正字符编码
            fileOS = new FileOutputStream("F:\\ProgramData\\JavaReview\\src\\network\\tcp\\src\\receive.jpg");
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = stream.read(buffer))!=-1) {
                fileOS.write(buffer,0,len);
            }

            //强化，通知客户端接收完毕
            out.write("Recieve over!".getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            if (fileOS!=null) {
                try {
                    fileOS.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (stream!=null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out!=null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
